<template>
  <view class="root">
    <view class="bgc-fff pl-30 pr-30 mt-30">
      <label class="ai-center height-90 fs-30 bb-eb">
        <image
          class="width-36 height-36"
          src="/static/imgs/icon-community_.png"
        />
        <input
          v-model="model.title"
          class="pl-30 pr-30 f1 fs-30"
          placeholder-class="color-8f9aa8"
          placeholder="请输入社群名称（例如李师家电维修）"
        />
      </label>
      <label class="ai-center height-90 fs-30 bb-eb">
        <image class="width-36 height-36" src="/static/imgs/icon-phone.png" />
        <input
          v-model="model.tel"
          class="input pl-30 pr-30 f1 fs-30"
          placeholder-class="color-8f9aa8"
          placeholder="请输入联系方式（选填）"
          type="number"
          maxlength="11"
        />
      </label>

      <textarea
        v-model="model.text"
        class="introduction fs-28"
        placeholder-class="color-8f9aa8"
        placeholder="请输入社群简介，便于成员更好的了解该社群"
      />
      <view class="show-picture fd-row mb-30">
        <view v-if="model.avatar || avatar" class="picture">
          <image
            class="icon-delete width-40 height-40 absolute right-0 top-0"
            src="/static/imgs/icon-delete.png"
            @click="operationImage('delete')"
          />
          <image
            class="width-100percent height-100percent absolute top-0 left-0"
            :src="model.avatar || avatar"
            mode="aspectFit"
            @click="operationImage('preview')"
          />
        </view>
        <view v-else @click="operationImage('choose')" class="picture last">
          <image
            class="absolute width-40 height-36"
            src="/static/imgs/icon-camera.png"
          />
        </view>
      </view>
    </view>
    <text class="fs-24 mt-30 mb-30 ml-20 mr-20 color-8f9aa8">选择展示社区</text>
    <scroll-view
      style="overflow: hidden"
      @scrolltolower="getCommunityData"
      scroll-y
      class="communities bgc-fff"
    >
      <checkbox-group @change="changeCheckbox">
        <label
          v-for="(item, index) in communities.lists"
          :key="index"
          class="ai-center jc-sb height-90 ml-30 mr-30"
        >
          <label class="ai-center">
            <image
              class="width-36 height-36"
              src="/static/imgs/icon-community_.png"
            />
            <text class="ml-18 fs-30 color-333">{{ item.name }}</text>
          </label>
          <view class="fd-row ai-center">
            <text class="fs-28 color-8f9aa8">{{ item.km }}km</text>
            <checkbox
              class="ml-26"
              color="#4388e7"
              :value="item.bid.toString()"
              :checked="model.bids.includes(item.bid)"
            />
          </view>
        </label>
      </checkbox-group>

      <load-more :status="loadMoreStatus" />
    </scroll-view>

    <view
      hover-class="btn-hover"
      @click="editGroup"
      :class="[
        `f1 confirm color-fff fs-36 fw-500 fixed width-100vw height-100 bottom-0 fd-row ai-center jc-center`,
      ]"
    >
      {{ group_id ? "修改" : "创建" }}社群
    </view>
  </view>
</template>

<script>
  import loadMore from "@/components/load-more";
  export default {
    data: () => ({
      model: {
        title: "",
        text: "",
        bids: "",
        tel: "",
        avatar: "",
      },
      location: [],
      avatar: "",
      communities: { page: 1, lists: [] },
      loadMoreStatus: "loading",
      community_id: 0,
      group_id: 0,
    }),
    components: { loadMore },
    onLoad({ community_id, group_id }) {
      this.community_id = community_id;
      this.group_id = group_id;

      group_id && this.getGroupData(group_id);

      uni.getLocation({
        success: ({ latitude, longitude }) => {
          this.location = [latitude, longitude];
          this.getCommunityData(community_id || 0);
        },
        fail: () =>
          uni.showToast({
            title: "获取位置信息失败, 请允许相关权限后重试",
            icon: "none",
          }),
      });
    },
    methods: {
      operationImage(mode) {
        switch (mode) {
          case "delete":
            this.model.avatar = this.avatar = "";
            break;
          case "preview":
            uni.previewImage({
              current: 0,
              urls: [this.avatar || this.model.avatar],
              indicator: "number",
            });
            break;
          default:
            uni.chooseImage({
              count: 1,
              success: (res) => {
                this.model.avatar = res.tempFilePaths[0];
              },
            });
            break;
        }
      },
      getCommunityData() {
        const { communities, location } = this;
        if (!communities.page) return;

        this.loadMoreStatus = "loading";

        uni.fetch("/api/login/nearby_community", {
          data: {
            latitude: location[0],
            longitude: location[1],
            limit: 8,
            page: this.communities.page,
            keyword: "",
            community_id: this.community_id,
            group_id: this.group_id,
          },
          success: (res) => {
            this.communities.page = res.page;
            res.lists && this.communities.lists.push(...(res.lists || []));
            this.loadMoreStatus = res.page ? "more" : "noMore";
          },
        });
      },
      getGroupData() {
        uni.fetch("/api/login/group_detail", {
          method: "GET",
          data: { bid: this.group_id },
          success: (res) => {
            Object.keys(res).forEach((key) => {
              if (key === "avatar") return;
              this.model[key] = res[key];
            });
            this.avatar = res.avatar;
          },
        });
      },

      changeCheckbox({ detail }) {
        this.model.bids = detail.value.toString();
      },
      async editGroup() {
        uni.showLoading({ title: "Loading...", mask: true });

        const submit = (avatar) => {
          uni.fetch("/api/group/edit", {
            data: { ...this.model, bid: this.group_id, avatar },
            success: ({ msg: title }) =>
              uni.showToast({
                title,
                success: () => setTimeout(uni.navigateBack, 1500),
              }),
          });
        };

        if (!this.model.avatar) {
          submit(this.avatar);
          return;
        }

        let [fail, success] = await uni.uploadFile({
          url: uni.REQUEST_URL + "/api/file/media",
          filePath: this.model.avatar,
          maxDuration: 15,
          name: "file",
          formData: { token: uni.getStorageSync("userInfo").token },
        });

        if (fail) {
          uni.showToast({ title: fail.errMsg, icon: "none" });
          return;
        }

        const { data, code, msg } = JSON.parse(success.data);

        if (code !== 200) {
          uni.showToast({ title: msg, icon: "none" });
          return;
        }

        submit(data.path);
      },
    },
  };
</script>

<style>
  .introduction {
    width: 100%;
    height: 160rpx;
    padding: 30rpx 0;
  }
  .bb-eb {
    border-bottom: 1rpx solid #ebebeb;
  }
  .confirm {
    background: linear-gradient(90deg, #8ec5fc, #4388e7);
  }
  .communities {
    max-height: 150px;
  }
  .show-picture {
    flex-wrap: wrap;
  }
  .picture {
    overflow: hidden;
    position: relative;
    width: calc((100% - 96rpx) / 4);
    padding-bottom: calc((100% - 96rpx) / 4);
    margin: 12rpx;
    border-radius: 5rpx;
    height: 0;
  }
  .icon-delete {
    z-index: 9;
  }
  .picture.last {
    background-color: #f7f7f7;
    border: 1rpx solid #e6e6e6;
    border-radius: 5rpx;
    align-items: center;
  }
  .picture.last image {
    top: 50%;
    transform: translateY(-50%);
  }
</style>